from decimal import Decimal
from typing import List, Optional, Tuple

from tortoise.transactions import atomic

from app.core.constants import BalanceSourceType, PointSourceType
from app.models.user_model import UserBalanceRecordModel, UserModel, UserPointRecordModel
from app.schemas.balance_point import BalanceRecordResponse, PointRecordResponse, UserBalanceRecordResponse
from app.schemas.common import OrderSchema, PaginationParams, PaginationResult
from app.services.base import BaseService


class BalancePointService(BaseService):
    """余额和积分服务"""

    @atomic()
    async def modify_balance(
        self, user_id: int, amount: Decimal, source_type: BalanceSourceType, remark: Optional[str] = None
    ) -> Tuple[bool, str]:
        """
        修改用户余额

        Args:
            user_id: 用户ID
            amount: 变动金额（正数增加，负数减少）
            source_type: 来源类型
            remark: 备注

        Returns:
            (success, message)
        """
        user = await UserModel.get_or_none(id=user_id)
        if not user:
            return False, "用户不存在"

        # 如果是减少余额，检查余额是否足够
        if amount < 0 and abs(amount) > user.balance:
            return False, "余额不足"

        before_balance = user.balance
        after_balance = before_balance + amount

        # 创建余额记录
        await UserBalanceRecordModel.create(
            user=user,
            amount=amount,
            before_balance=before_balance,
            after_balance=after_balance,
            source_type=source_type,
            remark=remark,
        )

        # 更新用户余额
        user.balance = after_balance
        await user.save()

        return True, "操作成功"

    async def modify_points(
        self, user_id: int, amount: int, source_type: PointSourceType, remark: Optional[str] = None
    ) -> Tuple[bool, str]:
        """
        修改用户积分

        Args:
            user_id: 用户ID
            amount: 变动积分（正数增加，负数减少）
            source_type: 来源类型
            remark: 备注

        Returns:
            (success, message)
        """
        user = await UserModel.get_or_none(id=user_id)
        if not user:
            return False, "用户不存在"

        # 如果是减少积分，检查积分是否足够
        if amount < 0 and abs(amount) > user.points:
            return False, "积分不足"

        before_points = user.points
        after_points = before_points + amount

        # 创建积分记录
        await UserPointRecordModel.create(
            user=user,
            amount=amount,
            before_points=before_points,
            after_points=after_points,
            source_type=source_type,
            remark=remark,
        )

        # 更新用户积分
        user.points = after_points
        await user.save()

        return True, "操作成功"


class BalanceCRUDService(BaseService):
    """余额CRUD服务"""
    async def list_balance_records(
        self, order: OrderSchema, pagination: PaginationParams, filters: Optional[OrganizationFilters] = None
    ) -> PaginationResult[UserBalanceRecordResponse]:
        """获取组织架构列表"""
        special_filter_conditions = {
            "name__icontains": {"name__icontains": filters.name},
        }

   
        """获取余额记录"""
        return await self.list_items(
            model=UserBalanceRecordModel,
            filters=filters,
            order=order,
            pagination=pagination,
            special_filter_conditions=special_filter_conditions,
            list_schema=PaginationResult[UserBalanceRecordResponse],
        )

    async def get_balance_record(self, record_id: int) -> UserBalanceRecordResponse:
        """获取余额记录"""
        return await self.get_item(
            model=UserBalanceRecordModel,
            id=record_id,
            schema=UserBalanceRecordResponse,
        )


class PointCRUDService(BaseService):
    """积分CRUD服务"""

    async def get_point_records(
        self, user_id: int, pagination: PaginationParams
    ) -> PaginationResult[PointRecordResponse]:
        """获取积分记录"""
        pass

    async def get_point_record(self, record_id: int) -> PointRecordResponse:
        """获取积分记录"""
        pass
